const express = require('express');
const router = express.Router();
const Joi = require('joi');
const bcrypt = require('bcryptjs');
const db = require('../../models');
const { authenticateToken } = require('../../middleware/auth');
const { success, error, validationError, notFound, conflict } = require('../../utils/response');

// 输入验证规则
const updateProfileSchema = Joi.object({
  nickname: Joi.string().max(50).optional(),
  avatar: Joi.string().uri().optional(),
  theme_preference: Joi.string().valid('light', 'dark', 'auto').optional()
});

const changePasswordSchema = Joi.object({
  old_password: Joi.string().required(),
  new_password: Joi.string().min(6).max(128).required(),
  confirm_password: Joi.string().valid(Joi.ref('new_password')).required()
});

/**
 * 获取当前用户信息
 * GET /api/users/profile
 */
router.get('/profile', authenticateToken, async (req, res) => {
  try {
    const user = req.user;

    // 获取用户统计信息
    const [diaryCount, categoryCount, tagCount] = await Promise.all([
      db.Diary.count({ where: { user_id: user.id } }),
      db.Category.count({ where: { user_id: user.id } }),
      db.Tag.count({ where: { user_id: user.id } })
    ]);

    const userProfile = {
      ...user.toJSON(),
      stats: {
        diary_count: diaryCount,
        category_count: categoryCount,
        tag_count: tagCount
      }
    };

    return success(res, userProfile);

  } catch (err) {
    console.error('获取用户信息错误:', err);
    return error(res, '获取用户信息失败', 500);
  }
});

/**
 * 更新用户资料
 * PUT /api/users/profile
 */
router.put('/profile', authenticateToken, async (req, res) => {
  try {
    // 输入验证
    const { error: validationErr, value } = updateProfileSchema.validate(req.body);
    if (validationErr) {
      return validationError(res, '输入数据不合法', validationErr.details[0].message);
    }

    const user = req.user;

    // 更新用户信息
    await user.update(value);

    return success(res, user.toJSON(), '用户资料更新成功');

  } catch (err) {
    console.error('更新用户资料错误:', err);
    return error(res, '更新用户资料失败', 500);
  }
});

/**
 * 修改密码
 * PUT /api/users/password
 */
router.put('/password', authenticateToken, async (req, res) => {
  try {
    // 输入验证
    const { error: validationErr, value } = changePasswordSchema.validate(req.body);
    if (validationErr) {
      return validationError(res, '输入数据不合法', validationErr.details[0].message);
    }

    const { old_password, new_password } = value;
    const user = req.user;

    // 获取完整用户信息（包含密码）
    const fullUser = await db.User.findByPk(user.id);

    // 验证旧密码
    const isValidPassword = await bcrypt.compare(old_password, fullUser.password);
    if (!isValidPassword) {
      return error(res, '原密码错误', 400);
    }

    // 加密新密码
    const saltRounds = parseInt(process.env.BCRYPT_ROUNDS) || 12;
    const hashedPassword = await bcrypt.hash(new_password, saltRounds);

    // 更新密码
    await fullUser.update({ password: hashedPassword });

    return success(res, null, '密码修改成功');

  } catch (err) {
    console.error('修改密码错误:', err);
    return error(res, '修改密码失败', 500);
  }
});

/**
 * 获取用户统计数据
 * GET /api/users/stats
 */
router.get('/stats', authenticateToken, async (req, res) => {
  try {
    const user_id = req.user.id;

    // 基础统计
    const [diaryCount, categoryCount, tagCount, imageCount] = await Promise.all([
      db.Diary.count({ where: { user_id } }),
      db.Category.count({ where: { user_id } }),
      db.Tag.count({ where: { user_id } }),
      db.Image.count({ where: { user_id } })
    ]);

    // 最近7天日记数量
    const sevenDaysAgo = new Date();
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);

    const recentDiaryCount = await db.Diary.count({
      where: {
        user_id,
        created_at: {
          [db.Sequelize.Op.gte]: sevenDaysAgo
        }
      }
    });

    // 本月日记数量
    const currentMonth = new Date();
    currentMonth.setDate(1);
    currentMonth.setHours(0, 0, 0, 0);

    const monthlyDiaryCount = await db.Diary.count({
      where: {
        user_id,
        created_at: {
          [db.Sequelize.Op.gte]: currentMonth
        }
      }
    });

    // 总浏览次数
    const totalViews = await db.Diary.sum('view_count', {
      where: { user_id }
    }) || 0;

    // 最受欢迎的分类
    const popularCategory = await db.Category.findOne({
      where: { user_id },
      attributes: [
        'id',
        'name',
        'color',
        'icon',
        [db.sequelize.fn('COUNT', db.sequelize.col('diaries.id')), 'diary_count']
      ],
      include: [
        {
          model: db.Diary,
          as: 'diaries',
          attributes: [],
          required: true
        }
      ],
      group: ['Category.id'],
      order: [[db.sequelize.fn('COUNT', db.sequelize.col('diaries.id')), 'DESC']],
      limit: 1
    });

    // 最受欢迎的标签
    const popularTag = await db.Tag.findOne({
      where: { user_id },
      attributes: [
        'id',
        'name',
        'color',
        [db.sequelize.fn('COUNT', db.sequelize.col('diaries.id')), 'usage_count']
      ],
      include: [
        {
          model: db.Diary,
          as: 'diaries',
          attributes: [],
          required: true
        }
      ],
      group: ['Tag.id'],
      order: [[db.sequelize.fn('COUNT', db.sequelize.col('diaries.id')), 'DESC']],
      limit: 1
    });

    const stats = {
      basic: {
        diary_count: diaryCount,
        category_count: categoryCount,
        tag_count: tagCount,
        image_count: imageCount,
        total_views: totalViews
      },
      recent: {
        last_7_days: recentDiaryCount,
        this_month: monthlyDiaryCount
      },
      popular: {
        category: popularCategory || null,
        tag: popularTag || null
      }
    };

    return success(res, stats);

  } catch (err) {
    console.error('获取用户统计错误:', err);
    return error(res, '获取用户统计失败', 500);
  }
});

/**
 * 获取用户活动时间线
 * GET /api/users/timeline
 */
router.get('/timeline', authenticateToken, async (req, res) => {
  try {
    const user_id = req.user.id;
    const { limit = 20 } = req.query;

    // 获取最近的日记活动
    const diaries = await db.Diary.findAll({
      where: { user_id },
      attributes: ['id', 'title', 'diary_date', 'created_at', 'updated_at'],
      include: [
        {
          model: db.Category,
          as: 'category',
          attributes: ['name', 'color', 'icon']
        }
      ],
      order: [['created_at', 'DESC']],
      limit: parseInt(limit)
    });

    // 转换为时间线格式
    const timeline = diaries.map(diary => ({
      id: diary.id,
      type: 'diary',
      title: diary.title,
      date: diary.diary_date,
      created_at: diary.created_at,
      updated_at: diary.updated_at,
      category: diary.category,
      action: diary.created_at.getTime() === diary.updated_at.getTime() ? 'created' : 'updated'
    }));

    return success(res, timeline);

  } catch (err) {
    console.error('获取用户时间线错误:', err);
    return error(res, '获取用户时间线失败', 500);
  }
});

/**
 * 删除用户账户
 * DELETE /api/users/account
 */
router.delete('/account', authenticateToken, async (req, res) => {
  try {
    const { password } = req.body;

    if (!password) {
      return validationError(res, '请输入密码确认删除账户');
    }

    const user = req.user;

    // 获取完整用户信息（包含密码）
    const fullUser = await db.User.findByPk(user.id);

    // 验证密码
    const isValidPassword = await bcrypt.compare(password, fullUser.password);
    if (!isValidPassword) {
      return error(res, '密码错误', 400);
    }

    // 删除用户账户（级联删除相关数据）
    await fullUser.destroy();

    return success(res, null, '账户删除成功');

  } catch (err) {
    console.error('删除用户账户错误:', err);
    return error(res, '删除用户账户失败', 500);
  }
});

/**
 * 导出用户数据
 * GET /api/users/export
 */
router.get('/export', authenticateToken, async (req, res) => {
  try {
    const user_id = req.user.id;

    // 获取用户所有数据
    const [user, categories, tags, diaries] = await Promise.all([
      db.User.findByPk(user_id, {
        attributes: { exclude: ['password'] }
      }),
      db.Category.findAll({ where: { user_id } }),
      db.Tag.findAll({ where: { user_id } }),
      db.Diary.findAll({
        where: { user_id },
        include: [
          {
            model: db.Category,
            as: 'category',
            attributes: ['name', 'color', 'icon']
          },
          {
            model: db.Tag,
            as: 'tags',
            attributes: ['name', 'color'],
            through: { attributes: [] }
          },
          {
            model: db.Image,
            as: 'images',
            attributes: ['filename', 'original_name', 'file_path']
          }
        ]
      })
    ]);

    const exportData = {
      user: user.toJSON(),
      categories,
      tags,
      diaries,
      exported_at: new Date().toISOString(),
      version: '1.0'
    };

    return success(res, exportData, '数据导出成功');

  } catch (err) {
    console.error('导出用户数据错误:', err);
    return error(res, '导出用户数据失败', 500);
  }
});

module.exports = router; 